package com.viethp.mt.activities;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.objects.CancelActivityResponse;
import com.viethp.mt.objects.UpdateActivityPriceResponse;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AGroupWantDetails extends Activity implements OnClickListener {

	private static final String ITEM_ID = "item_id";
	private static final String ACTIVITY_ID = "activity_id";
	private static final String ITEM_TITLE = "title";
	private static final String ITEM_DESCRIPTION = "description";
	private static final String ITEM_EXP = "expired";
	private static final String ITEM_PRICE = "price";
	private static final String TOTAL_BIDDER = "total_bidder";
	private static final String MAX_BUDGET = "max_budget";
	private static final String YOUR_PRICE = "your_price";
	private static final String ITEM_IMG_LINK = "imgLink";
	private static final String XML_STATUS = "status";

	private static final String PAYMENT_ITEM_NAME = "item_name";
	private static final String PAYMENT_ITEM_PRICE = "item_price";
	private static final String PAYMENT_ITEM_ID = "item_id";
	private static final String PAYMENT_ACTIVITY_ID = "activity_id";

	private static final int REQUEST_PAYMENT = 100;

	private Button btn_back, btn_post_edit, btn_post_del, btn_post_payment;
	private String item_id, title, desc, exp, price, imgLink, total_bidder,
			max_budget, your, activity_id, activity_status;
	private TextView tv_post_title, tv_post_exp, tv_post_price, tv_post_desc,
			tv_post_total_bidder, tv_post_max_budget, tv_post_your;
	private ImageView img;
	private EditText edt_update_price;
	private String update_price, update_max_budget;

	private ProgressDialog progressDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_want_details);

		Intent extras = getIntent();
		item_id = extras.getStringExtra(ITEM_ID);
		activity_id = extras.getStringExtra(ACTIVITY_ID);
		title = extras.getStringExtra(ITEM_TITLE);
		desc = extras.getStringExtra(ITEM_DESCRIPTION);
		exp = extras.getStringExtra(ITEM_EXP);
		price = extras.getStringExtra(ITEM_PRICE);
		imgLink = extras.getStringExtra(ITEM_IMG_LINK);
		total_bidder = extras.getStringExtra(TOTAL_BIDDER);
		max_budget = extras.getStringExtra(MAX_BUDGET);
		your = extras.getStringExtra(YOUR_PRICE);
		activity_status = extras.getStringExtra(XML_STATUS);

		GlobalVariables.ACTIVITY_ID = Integer.parseInt(activity_id);
		GlobalVariables.ITEM_ID = Integer.parseInt(item_id);

		initComponents();
		setOnClickListener();
		setInfo();
		checkEXP();
	}

	public void checkEXP() {
		if (Integer.parseInt(exp) == -1) {
			btn_post_edit.setEnabled(false);
			btn_post_payment.setVisibility(View.INVISIBLE);
		}
	}

	public void setInfo() {
		tv_post_title.setText(title);
		tv_post_exp.setText(CommonHelper.timeLeft(Long.parseLong(exp)));
		tv_post_price.setText("$" + price);
		tv_post_desc.setText(desc);
		tv_post_total_bidder.setText(total_bidder);
		tv_post_max_budget.setText("$" + max_budget);
		tv_post_your.setText(your);
		Bitmap bm = CommonHelper.getImageBitmap(imgLink);
		img.setImageBitmap(bm);
	}

	public void initComponents() {

		img = (ImageView) findViewById(R.id.img_post_image);

		tv_post_title = (TextView) findViewById(R.id.tv_post_title);
		tv_post_exp = (TextView) findViewById(R.id.tv_post_exp);
		tv_post_price = (TextView) findViewById(R.id.tv_post_price);
		tv_post_desc = (TextView) findViewById(R.id.tv_post_desc);
		tv_post_total_bidder = (TextView) findViewById(R.id.tv_post_total_bidder);
		tv_post_max_budget = (TextView) findViewById(R.id.tv_post_max_budget);
		tv_post_your = (TextView) findViewById(R.id.tv_post_your);

		btn_back = (Button) findViewById(R.id.btn_back);
		btn_post_edit = (Button) findViewById(R.id.btn_post_edit);
		btn_post_del = (Button) findViewById(R.id.btn_post_del);
		btn_post_payment = (Button) findViewById(R.id.btn_post_payment);
		checkPayment(Integer.parseInt(activity_status));

		progressDialog = new ProgressDialog(AGroupWantDetails.this);
		progressDialog.setCancelable(false);
	}

	public void setOnClickListener() {
		btn_back.setOnClickListener(this);
		btn_post_edit.setOnClickListener(this);
		btn_post_del.setOnClickListener(this);
		btn_post_payment.setOnClickListener(this);
	}

	public void checkPayment(int status) {
		if (status != 2) {
			btn_post_payment.setVisibility(View.INVISIBLE);
		} else
			btn_post_payment.setVisibility(View.VISIBLE);
		if (status == 3) {
			btn_post_edit.setVisibility(View.INVISIBLE);
			btn_post_del.setVisibility(View.INVISIBLE);
		} else if (status == 4) {
			btn_post_edit.setVisibility(View.INVISIBLE);
			// btn_post_del.setVisibility(View.INVISIBLE);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			this.finish();
			break;
		case R.id.btn_post_edit:
			DialogUpdateActivityPrice();
			break;
		case R.id.btn_post_del:
			showLCancelConfirm().show();
			break;
		case R.id.btn_post_payment:
			Intent intent = new Intent(AGroupWantDetails.this,
					APaymentMethod.class);
			intent.putExtra(PAYMENT_ITEM_NAME, title);
			intent.putExtra(PAYMENT_ITEM_PRICE, your);
			intent.putExtra(PAYMENT_ITEM_ID, item_id);
			intent.putExtra(PAYMENT_ACTIVITY_ID, activity_id);
			startActivityForResult(intent, REQUEST_PAYMENT);
			break;
		default:
			break;
		}

	}

	public void DialogUpdateActivityPrice() {

		LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_set_price,
				null);

		edt_update_price = (EditText) view.findViewById(R.id.edt_set_price);
		edt_update_price.setHint("Update your price");
		edt_update_price.setInputType(InputType.TYPE_CLASS_NUMBER);

		final Dialog dia = new Dialog(this);
		dia.setContentView(view);
		dia.setTitle("Update your price");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);

		if (String.valueOf(edt_update_price.getText()).equals(""))
			btn_change.setEnabled(false);
		edt_update_price.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (String.valueOf(edt_update_price.getText()).equals(""))
					btn_change.setEnabled(false);
				else
					btn_change.setEnabled(true);
			}
		});

		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				update_price = String.valueOf(edt_update_price.getText())
						.trim();
				Log.d("phone", update_price);
				doUpdatePrice();
				dia.dismiss();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

	public void doUpdatePrice() {
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallServiceUpdateActivityPrice();
		} else
			CommonHelper.showWarning(AGroupWantDetails.this,
					getString(R.string.netstate));
	}

	public void startCallServiceUpdateActivityPrice() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callServiceUpdateActivityPrice();
				handlerUpdateActivityPrice.sendMessage(message);

			}
		}).start();
	}

	private UpdateActivityPriceResponse callServiceUpdateActivityPrice() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_UPDATE_ACTIVITY_PRICE);
		userRequest.addProperty("activity_id", GlobalVariables.ACTIVITY_ID);
		userRequest.addProperty("price", GlobalVariables.ITEM_ID);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_UPDATE_ACTIVITY_PRICE);
		request.addProperty(GlobalVariables.WS_METHOD_UPDATE_ACTIVITY_PRICE,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport
					.call(GlobalVariables.WS_NAMESPACE
							+ GlobalVariables.WS_METHOD_UPDATE_ACTIVITY_PRICE,
							envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_UPDATE_ACTIVITY_PRICE,
						envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}

		return new UpdateActivityPriceResponse(results);

	}

	private Handler handlerUpdateActivityPrice = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				UpdateActivityPriceResponse response = (UpdateActivityPriceResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(AGroupWantDetails.this, response
							.getErrorCode().getErrMsg());
				} else {
					update_max_budget = String.valueOf(response.getMaxBudget());
					tv_post_your.setText(update_price);
					tv_post_max_budget.setText(update_max_budget);
					CommonHelper.showWarning(AGroupWantDetails.this,
							"Update successful");
				}

			} else {
				CommonHelper.showWarning(AGroupWantDetails.this,
						getString(R.string.disconnect));
			}

		};
	};

	protected Dialog showLCancelConfirm() {
		return new android.app.AlertDialog.Builder(this)
				.setMessage(getString(R.string.cancel_confirm))
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								doCancel();
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(android.content.DialogInterface dialog,
							int whichButton) {
					}
				}).create();
	}

	public void doCancel() {
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallServiceCancel();
		} else
			CommonHelper.showWarning(AGroupWantDetails.this,
					getString(R.string.netstate));
	}

	public void startCallServiceCancel() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callServiceCancel();
				handlerCancel.sendMessage(message);

			}
		}).start();
	}

	private CancelActivityResponse callServiceCancel() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_CANCEL_ACTIVITY);
		// userRequest.addProperty("user_id",
		// CommonHelper.getUserLogin(AGroupWantDetails.this).getId());
		// userRequest.addProperty("item_id", item_id);
		userRequest.addProperty("activity_id", activity_id);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_CANCEL_ACTIVITY);
		request.addProperty(GlobalVariables.WS_METHOD_CANCEL_ACTIVITY,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_CANCEL_ACTIVITY, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_CANCEL_ACTIVITY, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}

		return new CancelActivityResponse(results);

	}

	private Handler handlerCancel = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				CancelActivityResponse response = (CancelActivityResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(AGroupWantDetails.this, response
							.getErrorCode().getErrMsg());
				} else {
					//
					CommonHelper.showToast(AGroupWantDetails.this,
							"Cancel successful");
					// Intent intent = getIntent();
					// intent.putExtra("cancel_status", "cancel");
					// setResult(RESULT_OK, intent);
					finishForResult();
				}

			} else {
				CommonHelper.showWarning(AGroupWantDetails.this,
						getString(R.string.disconnect));
			}

		};
	};

	public void finishForResult() {
		Intent intent = getIntent();
		intent.putExtra("cancel_status", "cancel");
		setResult(RESULT_OK, intent);
		this.finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_PAYMENT) {
				int payment_status = Integer.parseInt(data
						.getStringExtra("payment_status"));
				if (payment_status == 1)
					btn_post_payment.setVisibility(View.GONE);
			}
		}
	}
}
